import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class Requestmiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: () => void) {
    if (req?.body?.noMsg) {
      delete req?.body?.noMsg;
    }
    if (req?.body?.noThrottle) {
      delete req?.body?.noThrottle;
    }
    Object.keys(req.body).map(item => {
      if (
        req.body[item] === 'undefined' ||
        req.body[item] === 'null' 
        // ||
        // // req.body[item] === '' ||
        // (Array.isArray(req.body[item]) && req.body[item].length === 0)
      ) {
        delete req.body[item];
      }
    });
    Object.keys(req.query).map(item => {
      if (
        req.query[item] === 'undefined' ||
        req.query[item] === 'null' 
        // ||
        // // req.query[item] === '' ||
        // (Array.isArray(req.query[item]) && req.query[item].length === 0)
      ) {
        delete req.query[item];
      }
    });
    // 表格排序参数序列化
    if (req.body?.orderParam) {
      let orderParam = req.body?.orderParam;
      Object.keys(orderParam).map(item => {
        orderParam[item] = orderParam[item].toLocaleUpperCase();
        if (orderParam[item].indexOf('DESC') !== -1) {
          orderParam[item] = 'DESC';
        } else {
          orderParam[item] = 'ASC';
        }
      });
      req.body.orderParam = orderParam;
    }

    // req.next()
    const { method, path } = req;
    console.log(`${method} ${path}`);
    next();
  }
}
